package cn.school.mybatis.dao;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import cn.school.mybatis.pojo.Subject;

public class TestSubject {

	public static void main(String[] args) throws IOException {
		// 1、读取核心的配置文件
		// String resource = "mybatis-config.xml";
		// InputStream inputStream = Resources.getResourceAsStream(resource);
		// 构建SqlSessionFactory
		// SqlSessionFactory sqlSessionFactory = new
		// SqlSessionFactoryBuilder().build(inputStream);
		// 打开链接
		// SqlSession session = sqlSessionFactory.openSession();

		SqlSession session = MyBatisUtil.getSqlSession();
		// 获得映射接口的实现类
		// 动态代理的生成的一个类
		// 原理是运行时生成一个SubjectDao接口的实现类
		SubjectDao subjectDao = session.getMapper(SubjectDao.class);
		// System.out.println(subjectDao.getClass().getName());

		// 修改
//		Subject subject = new Subject(63, "mybatis-3", 20, 3);
//		int result = subjectDao.update(subject);
//		session.commit();
//		System.out.println(result + "条修改成功！");

		// 删除
//		int result = subjectDao.del(63);
//		session.commit();
//		System.out.println(result + "条删除成功！");

		// 增加
//		Subject subject = new Subject("mybatis-2", 20, 3);
//		int result = subjectDao.add(subject);
//		session.commit();
//		System.out.println(result + "条增加成功！");
		// 查询数量
		// int count = subjectDao.searchCount();
		// System.out.println("共有" + count + "条记录");

		// 查询全部
		// List<Subject> list = subjectDao.searchAll();
		// for (Subject s : list) {
		// System.out.print(s);
		// }

		// 分页查询
		int pageNo = 2;
		int pageSize = 5;

		int offset = (pageNo - 1) * pageSize;
		offset = Math.max(offset, 0);
		Map<String, Object> map = new HashMap<>();
		map.put("pageNo", offset);
		map.put("pageSize", pageSize);

		List<Subject> list = subjectDao.search(map);
		for (Subject s : list) {
			System.out.print(s);
		}

		// 查询单个
//		Subject result = subjectDao.get(48);
//		System.out.println(result);

		// 关闭
		MyBatisUtil.close(session);
	}

}
